<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { reactive } from 'vue'
import { ref } from 'vue'
import { getSequenceApi, appSaveFormApi } from '@/api/system'
import { usetreeStore } from '@/stores/index'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { appType } from '@/views/system/dictionary'
import { convertTreeLabel } from '@/utils/publicMethods'
// import { onMounted } from 'vue'

const props = defineProps<{
  isShow: boolean
  title: string
  formInfo: any
}>()

const emit = defineEmits<{
  (e: 'update:isShow', value: boolean): void
  (e: 'getYingYongTree'): void
}>()

const defaultProps = {
  children: 'children',
  label: 'label',
  value: 'value',
  disabled: function (data: any, node: any) {
    if (node && node.level > 1) {
      return false
    } else {
      return true
    }
  }
}
const treeStore = usetreeStore()

const subClsTreeArry = JSON.parse(JSON.stringify(convertTreeLabel(treeStore.appTreeList)))
// 树结构懒加载
const subClsTreeFn = (node: Node, resolve: (data: any[]) => void) => {
  // console.log(node)
  // 树形结构地域
  if (node.level === 0) {
    const info = subClsTreeArry.map((item: any) => {
      return {
        value: item.value,
        label: item.label,
        children: item.children
      }
    })
    return resolve(info)
  }

  if (node.level > 1) {
    if (!node.data.children) {
      return resolve([])
    } else {
      setTimeout(() => {
        const data = node.data.children
        resolve(data)
      }, 500)
    }
  }
  setTimeout(() => {
    const data = node.data.children
    resolve(data)
  }, 500)
}
interface RuleForm {
  app_name: string
  app_order: string
  app_class: any
  open_type: string
  app_url: string
  app_description: string
  req_user: string
  req_dept: string
  req_date: any
  creator: string
  req_id: string
}
const rules = reactive<FormRules<RuleForm>>({
  app_name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  app_order: [{ required: true, message: '请输入应用排序', trigger: 'blur' }],
  app_class: [{ required: true, message: '请输入应用归类', trigger: 'blur' }],
  open_type: [{ required: true, message: '请输入应用归类', trigger: 'blur' }],
  app_url: [{ required: true, message: '请输入应用地址', trigger: 'blur' }],
  app_description: [{ required: true, message: '请输入应用描述', trigger: 'blur' }],
  req_user: [{ required: true, message: '请输入提出人', trigger: 'blur' }],
  req_dept: [{ required: true, message: '请输入提出部门', trigger: 'blur' }],
  req_date: [{ required: true, message: '请输入提出日期', trigger: 'blur' }],
  creator: [{ required: true, message: '请输入创建人', trigger: 'blur' }],
  req_id: [{ required: true, message: '请输入提出人ID', trigger: 'blur' }]
})

const ruleFormRef = ref<any>()
const form = ref<any>({
  app_id: '',
  app_class: undefined,
  app_name: '',
  app_order: undefined,
  open_type: undefined,
  app_url: '',
  app_description: '',
  req_user: '',
  req_dept: '',
  req_date: '',
  creator: '',
  req_id: '',
  is_show: '1'
})

if (props.title === '修改应用') {
  form.value = { ...props.formInfo }
  form.value.app_id = props.formInfo.app_id
  form.value.app_class = [Number(form.value.app_class)]
  form.value.app_description = props.formInfo.app_description
  form.value.app_name = props.formInfo.app_name
  form.value.app_order = props.formInfo.app_order
  form.value.open_type = props.formInfo.open_type
  form.value.app_url = props.formInfo.app_url
  form.value.req_user = props.formInfo.req_user
  form.value.req_dept = props.formInfo.req_dept
  form.value.req_date = props.formInfo.req_date
  form.value.creator = props.formInfo.creator
  form.value.req_id = props.formInfo.req_id
  form.value.is_show = String(props.formInfo.is_show)
}

// 获得应用ID
const getAppId = async () => {
  const params = {
    name: 'app_id',
    dbName: undefined
  }
  await getSequenceApi(params)
    .then((res: any) => {
      // console.log(res)
      form.value.app_id = res
    })
    .catch(() => {
      ElMessage({ message: '获得应用ID失败', type: 'error' })
    })
}

// 提交表单
const saveFormFn = async () => {
  props.title !== '修改应用' ? await getAppId() : ''
  const params = {
    sqlId:
      props.title === '新增应用'
        ? JSON.stringify(['appInfo.insertAppInfo', 'appInfo.insertAppClassRela'])
        : JSON.stringify([
            'appInfo.updateAppInfo',
            'appInfo.deleteAppClassRela',
            'appInfo.insertAppClassRela'
          ]),
    app_id: form.value.app_id,
    app_name: form.value.app_name,
    app_order: form.value.app_order,
    app_class:
      props.title === '新增应用'
        ? JSON.stringify([String(form.value.app_class[0])])
        : JSON.stringify([String(form.value.app_class[0])]),
    open_type: form.value.open_type,
    app_url: form.value.app_url,
    app_description: form.value.app_description,
    req_user: form.value.req_user,
    req_dept: form.value.req_dept,
    req_date: form.value.req_date,
    creator: form.value.creator,
    req_id: form.value.req_id,
    is_show: Number(form.value.is_show)
  }
  // console.log(params)
  await appSaveFormApi(params)
    .then((res: any) => {
      // console.log(res)
      if (res === 'success') {
        ElMessage({ message: '提交成功', type: 'success' })
        emit('update:isShow', false)
        emit('getYingYongTree')
      } else {
        ElMessage({ message: '提交失败', type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '提交失败', type: 'error' })
    })
}
// 取消
const Cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  emit('update:isShow', false)
}

// 确定
const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      saveFormFn()
    } else {
      ElMessage({ message: '请输入完整信息', type: 'error' })
    }
  })
}

// const getHuaXiaoTreeNode = (node: any) => {
//   if (form.value.app_class.length > 0) {
//     // console.log(node.label)

//     // form.value.hx_name = node.label
//   }
// }

// onMounted(() => {
//   getAppId()
// })
</script>
<template>
  <div>
    <el-dialog :model-value="true" :title="title" width="60%" @close="Cancel(ruleFormRef)">
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用名称:" prop="app_name">
              <el-input v-model="form.app_name" style="width: 300px" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用排序:" prop="app_order">
              <el-input
                v-model="form.app_order"
                style="width: 240px"
                type="number"
                placeholder="请输入排序"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用归类:" prop="app_class">
              <el-tree-select
                clearable
                lazy
                :load="subClsTreeFn"
                :data="subClsTreeArry"
                :props="defaultProps"
                v-model="form.app_class"
                multiple
                :multiple-limit="1"
                node-key="value"
                :render-after-expand="false"
                style="width: 300px"
                check-strictly
                check-on-click-node
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用类型:" prop="open_type">
              <el-select v-model="form.open_type" placeholder="请选择应用类型" style="width: 240px">
                <el-option
                  v-for="item in appType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="应用地址:" prop="app_url">
          <el-input
            v-model="form.app_url"
            placeholder="请输入应用地址 (多维报表统一路径样例：/multiDimensional?reportId=1)"
          />
        </el-form-item>
        <el-form-item label="应用描述:" prop="app_description">
          <el-input v-model="form.app_description" :rows="4" type="textarea" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="提出人:" prop="req_user">
              <el-input v-model="form.req_user" style="width: 240px" placeholder="请输入提出人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提出部门:" prop="req_dept">
              <el-input v-model="form.req_dept" style="width: 240px" placeholder="请输入提出部门" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提出时间:" prop="req_date">
              <el-date-picker
                v-model="form.req_date"
                type="date"
                placeholder="选择提出时间"
                value-format="YYYY-MM-DD"
                style="width: 240px"
              />
              <!-- <el-input v-model="form.req_date" style="width: 240px" placeholder="请输入提出时间" /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开发人:" prop="creator">
              <el-input v-model="form.creator" style="width: 240px" placeholder="请输入开发人" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求单号:" prop="req_id">
              <el-input v-model="form.req_id" style="width: 240px" placeholder="请输入需求单号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否导航中显示:" prop="is_show">
              <el-radio-group v-model="form.is_show">
                <el-radio value="1">是</el-radio>
                <el-radio value="0">否</el-radio>
              </el-radio-group>
              <!-- <el-input v-model="form.is_show" style="width: 240px" placeholder="请输入需求单号" /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="Confirm(ruleFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="less"></style>
